package archer.framework.groovy.console;

import archer.framework.utils.DateProcessor;
import archer.framework.utils.RandomUtils;
import groovy.lang.GroovyShell;
import jodd.io.FileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Groovy脚本执行器
 *
 * @author christ
 * @date 2015/7/6
 */
public class GroovyConsole extends HttpServlet {

    private static GroovyShell shell = new GroovyShell();

    private static final String TYPE_TEXT = "text";
    private static final String TYPE_FILE = "file";

    private String initKey;

    private static Logger logger = LoggerFactory.getLogger(GroovyConsole.class);


    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        initKey = config.getInitParameter("key");
    }

    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String key = req.getParameter("key");

        if (key == null || key.isEmpty()) {
            return;
        }

        if (!key.equals(initKey + DateProcessor.today().toString())) {
            return;
        }

        String type = req.getParameter("type");

        String param = req.getParameter("param");

        if (param == null || param.isEmpty()) {
            return;
        }

        if (type == null) {
            type = TYPE_TEXT;
        }

        String text = param;

        StringBuilder log = new StringBuilder();

        if (TYPE_FILE.equals(type)) {

            text = FileUtil.readString(param);

            log.append("Groovy Console >> file : ").append(param).append("\r\n");

        } else {

            log.append("Groovy Console >> text : ").append("\r\n");
        }


        Object result = shell.run(text, RandomUtils.randomAlpha(10), (String[]) null);

        log.append("-----------------------INPUT BEGIN--------------------------------").append("\r\n");

        log.append(text);

        log.append("\r\n");
        log.append("-----------------------INPUT END----------------------------------").append("\r\n");

        log.append("\r\n");
        log.append("-----------------------OUTPUT BEGIN-------------------------------").append("\r\n");

        if (result != null) {
            log.append(result.toString());
        }

        log.append("\r\n");
        log.append("-----------------------OUTPUT END---------------------------------").append("\r\n");

        logger.error(log.toString());

        if (result != null) {
            resp.getWriter().write(result.toString());
        }

    }
}
